/* $RCSFile: RegisterCRM.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/Register/RegisterCRM.ascx.cs $
 * $log$
 * Revision 27 2011/01/21 17:51:08  christian.surieux
 *   Recover from Sony move files updated in 11/2010 were not in Source Control
 * Revision 20 2010/08/09 10:51:22  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:59  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:26  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Globalization;

using AddonNice.Diagnostics;
using AddonNice.Core;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.Authentication;
using AddonNice.Settings;
using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.UI.Design;
using AddonNice.Helpers;
using AddonNice.Country;
using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.Register
{

/* DBG for ChildControlsCreated fla being reset when asigning MembershipProvider
    public class DUserControl : CreateUserWizard
    {

        protected override void CreateControlHierarchy()
        {
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DUserControl CreateControlHierarchy BEG ChildControlsCreated: {0}.", ChildControlsCreated ),SecurityTraceSwitch.Sw.Info);
            base.CreateControlHierarchy();
        }

        protected override void EnsureChildControls()
        {
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DUserControl EnsureChildControls BEG ChildControlsCreated: {0}.", ChildControlsCreated ),SecurityTraceSwitch.Sw.Info);
            base.EnsureChildControls();
        }

        protected override void CreateChildControls()
        {
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DUserControl CreateChildControls BEG ChildControlsCreated: {0}.", ChildControlsCreated ),SecurityTraceSwitch.Sw.Info);
            base.CreateChildControls();
        }

        public bool ChildCreated()
        { return ChildControlsCreated; }
    }

 */

    public class AStr
    {
        public const string ImpersonateUser      =   "REGISTERCRM_IMPERSONATE_USER";
        public const string ImpersonateUserDomain=   "REGISTERCRM_IMPERSONATE_USER_DOMAIN";
        public const string ImpersonateUserLogin =   "REGISTERCRM_IMPERSONATE_USER_LOGIN";
        public const string ImpersonateUserPwd   =   "REGISTERCRM_IMPERSONATE_USER_PWD";
        public const string CustomerType         =   "REGISTERCRM_CUSTOMER_TYPE";
        public const string MoreData             =   "REGISTERCRM_MORE_DATA";
        public const string LogAfterCreate       =   "REGISTERCRM_LOG_AFTERCREATE";
        public const string AddToProfile         =   "REGISTERCRM_ADD_TO_PROFILE";
        public const string DisableCreatedUser   =   "REGISTERCRM_DISABLE_CREATED_USER";
        public const string DisplayCancel        =   "REGISTERCRM_DISPLAYCANCEL";

        public const string WizardTitle          =   "REGISTERCRM_WIZARD_TITLE";
        public const string Username             =   "REGISTERCRM_USERNAME";
        public const string FirstName            =   "REGISTERCRM_FIRSTNAME";
        public const string Company              =   "REGISTERCRM_COMPANY";
        public const string Nickname             =   "REGISTERCRM_NICKNAME";
        public const string Address1             =   "REGISTERCRM_ADDRESS1";
        public const string Address2             =   "REGISTERCRM_ADDRESS2";
        public const string Address3             =   "REGISTERCRM_ADDRESS3";
        public const string City                 =   "REGISTERCRM_CITY";
        public const string Country              =   "REGISTERCRM_COUNTRY";
        public const string Zip                  =   "REGISTERCRM_ZIP";
        public const string State                =   "REGISTERCRM_STATE";
        public const string Phone                =   "REGISTERCRM_PHONE";
        public const string Fax                  =   "REGISTERCRM_FAX";
        public const string BillingInfo          =   "REGISTERCRM_BILLING";
        public const string ShippingInfo         =   "REGISTERCRM_SHIPPING";
    }
    /// <summary>
    /// Initializer class for RegisterCRM 
    /// </summary>
    public class RegisterCRMSI : PortalCRMModuleControlSI
    {
        public RegisterCRMSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]RegisterCRMSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]RegisterCRMSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]RegisterCRMSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            string extgrp                           =   pm.ExtendedResourcesGroup;

            // We need a new user to impersonates crm access with
            // customers created with this system user will also belong to it.
            WSListDataType defAcc                   =   new WSListDataType(CrmStr.systemuser,"name", "ID");
        	SettingItemSpecial ImpersonateUser      =   new SettingItemSpecial(AStr.ImpersonateUser,defAcc);
            ImpersonateUser.EnglishName             =   "Crm Impersonate user";
            // default == CRMDefaultAccount or first
            ADNDynSystemUser wsys                    =   null;
            if (!string.IsNullOrEmpty(Config.CRMDefaultAccount))
            {
                string domainName                   =   string.Format("{0}\\{1}",Config.CRMDefaultAccountDomain,Config.CRMDefaultAccount);
                wsys                                =   Wrapper.Util.FindSystemUserByDomainName(domainName);
            }
            if (wsys != null)
            {
                ImpersonateUser.Value               =   wsys.systemuserid.ToString();
                defAcc.DisplayTextValue             =   wsys.fullname;
            }
            ImpersonateUser.Required                =   true;
            ImpersonateUser.Order                   =   10;
			ImpersonateUser.ExtendedGroupName       =   extgrp;
            ImpersonateUser.Description             =   "Choose the Crm User that will be used to impersonate these new customers";
            bSettings.AddSetting(ImpersonateUser);

        	SettingItemSpecial ImpersonateUserDomain =  new SettingItemSpecial(AStr.ImpersonateUserDomain,new StringDataType());
            ImpersonateUserDomain.EnglishName       =   "Impersonate user Domain";
            ImpersonateUserDomain.Value             =   Config.CRMDefaultAccountDomain;
            ImpersonateUserDomain.Required          =   true;
            ImpersonateUserDomain.Order             =   12;
            ImpersonateUserDomain.ExtendedGroupName =   extgrp;
            ImpersonateUserDomain.Description       =   "Enter the Windows Domain this user log on";
            
            ImpersonateUserDomain.AddDependency(ImpersonateUser,ImpersonateUserChanged);
            
            bSettings.AddSetting(ImpersonateUserDomain);

            SettingItemSpecial ImpersonateUserLogin =   new SettingItemSpecial(AStr.ImpersonateUserLogin,new StringDataType());
            ImpersonateUserLogin.EnglishName        =   "Impersonate user Domain Login";
            ImpersonateUserLogin.Value              =   Config.CRMDefaultAccount;
            ImpersonateUserLogin.Required           =   true;
            ImpersonateUserLogin.Order              =   14;
            ImpersonateUserLogin.ExtendedGroupName  =   extgrp;
            ImpersonateUserLogin.Description        =   "Enter the Windows domain loging account of this user";
            bSettings.AddSetting(ImpersonateUserLogin);
            // Ajax will update this item when ImpersonateUSer change
            ImpersonateUser.DependentItems.Add(ImpersonateUserLogin);

            SettingItemSpecial ImpersonateUserPwd   =   new SettingItemSpecial(AStr.ImpersonateUserPwd,new StringDataType());
            ImpersonateUserPwd.EnglishName          =   "Impersonate user password";
            ImpersonateUserPwd.Required             =   true;
            ImpersonateUserPwd.Value                =   Config.CRMDefaultAccountPassword;
            ImpersonateUserPwd.Order                =   16;
            ImpersonateUserPwd.ExtendedGroupName    =   extgrp;
            ImpersonateUserPwd.Description          =   "Enter the Windows domain password to log with this user";
            bSettings.AddSetting(ImpersonateUserPwd);

            // Ajax will update this item when ImpersonateUSer change
            ImpersonateUser.DependentItems.Add(ImpersonateUserPwd);

            ImpersonateUserPwd.AddDataTypeDependency(new DataTypeEventHandler(ImpersonateUserPwd_Event));

            // Type of Customer to create: account, contact or lead
            ArrayList EntityLst		                =   new ArrayList();
            NameIntValueItem t                      =   new NameIntValueItem(LocalizeHelper.Localize("ENTITY_ACCOUNT_NAME","Account"),
                                                                                                    (int)ADNTypeCodes.Account);
            EntityLst.Add(t);
            t                                       =   new NameIntValueItem(LocalizeHelper.Localize("ENTITY_CONTACT_NAME","Contact"),
                                                                                                    (int)ADNTypeCodes.Contact);
            EntityLst.Add(t);
            t                                       =   new NameIntValueItem(LocalizeHelper.Localize("ENTITY_LEAD_NAME","Lead"),
                                                                                                        (int)ADNTypeCodes.Lead);
            EntityLst.Add(t);

            SettingItemSpecial CustomerType         =   new SettingItemSpecial(AStr.CustomerType,new CustomListDataType(EntityLst, "name", "ID"));
            CustomerType.Required                   =   true;
            CustomerType.Value                      =   ((int)ADNTypeCodes.Contact).ToString();
            CustomerType.Order                      =   20;
            CustomerType.ExtendedGroupName          =   extgrp;
            CustomerType.EnglishName                =   "Customer Type";
            CustomerType.Description                =   "Crm customer type to associate with users";
            bSettings.AddSetting(CustomerType);

            // Should we enter all data (addresses etc.)
            SettingItemSpecial MoreData             =   new SettingItemSpecial(AStr.MoreData,new BooleanDataType());
            MoreData.Order                          =   30;
            MoreData.ExtendedGroupName              =   extgrp;
            MoreData.Value                          =   "True";
            MoreData.EnglishName                    =   "More Data";
            MoreData.Description                    =   "Enter More data than the simple account email and pwd";
            bSettings.AddSetting(MoreData);
            
            // Should we disable new user, waiting for some administrative approbation ?
            SettingItemSpecial DisableCreatedUser   =   new SettingItemSpecial(AStr.DisableCreatedUser,new BooleanDataType());
            DisableCreatedUser.Order                =   40;
            DisableCreatedUser.ExtendedGroupName    =   extgrp;
            DisableCreatedUser.Value                =   "False";
            DisableCreatedUser.EnglishName          =   "Disable created user";
            DisableCreatedUser.Description          =   "Should the new account be disabled, waiting som further approbation";
            bSettings.AddSetting(DisableCreatedUser);
            
            // should we log user after creation
            SettingItemSpecial LogAfterCreate       =   new SettingItemSpecial(AStr.LogAfterCreate,new BooleanDataType());
            LogAfterCreate.Order                    =   50;
            LogAfterCreate.ExtendedGroupName        =   extgrp;
            LogAfterCreate.Value                    =   "True";
            LogAfterCreate.EnglishName              =   "Log user after create";
            LogAfterCreate.Description              =   "Should the new user be automatically logged after account creation";
            bSettings.AddSetting(LogAfterCreate);
            
            // should we add to profile
            SettingItemSpecial AddToProfile         =   new SettingItemSpecial(AStr.AddToProfile,new BooleanDataType());
            AddToProfile.Order                      =   60;
            AddToProfile.ExtendedGroupName          =   extgrp;
            AddToProfile.Value                      =   "True";
            AddToProfile.EnglishName                =   "Add to profile";
            AddToProfile.Description                =   "Should the new user be added to profile";
            bSettings.AddSetting(AddToProfile);

            // should we allow cancel Button
            SettingItemSpecial DisplayCancel        =   new SettingItemSpecial(AStr.DisplayCancel,new BooleanDataType());
            DisplayCancel.Order                     =   70;
            DisplayCancel.ExtendedGroupName         =   extgrp;
            DisplayCancel.Value                     =   "True";
            DisplayCancel.EnglishName               =   "Display Cancel button";
            DisplayCancel.Description               =   "Should display the cancel button";
            bSettings.AddSetting(DisplayCancel);

            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RegisterCRMSI InitSettings END.",SecurityTraceSwitch.Sw.Info);
        }
        #region handlers for settings events
        
        // Check pwd entered in settings against crm
        void ImpersonateUserPwd_Event(object sender,DataTypeEventArgs e)
        {
   		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRMSI ImpersonateUserPwd_Event BEG testing for e.newVal: '{0}', e.oldVal: '{1}', EventType: {2}.",
                    e.newVal,e.oldVal,e.EventType),SecurityTraceSwitch.Sw.Info);
            if  ( (e.newVal == string.Empty) || (e.EventType != DataTypeEventType.Changed ) )
            {
                    return;
            }
            string newpwd                           =   e.newVal;
            SettingItem settng                      =   Owner.Settings[AStr.ImpersonateUserLogin];
            Control Ctl                             =   settng.EditControl;
            SettingItem settng2                     =   Owner.Settings[AStr.ImpersonateUserDomain];
            Control Ctl2                            =   settng2.EditControl;
            if ( ( Ctl is RadTextBox ) && ( Ctl2 is RadTextBox ) )
            {
                string login                            =   ((RadTextBox)Ctl).Text;
                if ( login == string.Empty )
                    login                               =   settng.Value;
                if ( login == string.Empty )
                    return;
                string domain                           =   ((RadTextBox)Ctl2).Text;
                if ( domain == string.Empty )
                    domain                              =   settng2.Value;
                if ( domain == string.Empty )
                    return;
   		        if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRMSI ImpersonateUserPwd_Event testing for login: '{0}', domain: '{1}', newpwd: {2}.",
                        login,domain,newpwd),SecurityTraceSwitch.Sw.Info);

                if (!Wrapper.IsUserOk4Crm(domain,login,newpwd))
                {
       		        if (SecurityTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine("[V]RegisterCRMSI ImpersonateUserPwd_Event INVALID pwd.",SecurityTraceSwitch.Sw.Info);
                    // empty pwd when not Ok so validation should block 
                    Owner.Settings[AStr.ImpersonateUserPwd].Value   =   string.Empty;
                }
                else Owner.Settings[AStr.ImpersonateUserPwd].Value   =   newpwd; // pb with pwd field input which reset its value on postback
            }
        }

        /// <summary>
        /// When in Settings edition, impersonate user has changed-> change domain, reset pwd
        /// </summary>
        void ImpersonateUserChanged(object sender, SettingItemsEventArgs e)
        {
    		if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRMSI ImpersonateUserChanged called sender: {0}, e.Data: {1}",sender,e.Data),SecurityTraceSwitch.Sw.Info);
            if ( e.EventType != SettingItemsEventType.ParentChanged )
                return;
            if ( e.dataTypeEventArg.Args  is RadComboBoxSelectedIndexChangedEventArgs )
            {
                RadComboBoxSelectedIndexChangedEventArgs ev =   (RadComboBoxSelectedIndexChangedEventArgs)e.dataTypeEventArg.Args;
                Guid userId                                 =   new Guid(ev.Value);
                ADNDynSystemUser user                       =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,new ResetWrapperHandler(ResetWrapper),userId);
       		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRMSI ImpersonateUserChanged domainname: {0}",user.domainname),SecurityTraceSwitch.Sw.Info);
                string domainName                           =   user.domainname;
                int idx                                     =   domainName.LastIndexOf('\\');
                if (  idx != -1 )
                {
                    string domain                           =   domainName.Substring(0,idx);
                    string login                            =   domainName.Substring(idx+1);
       		        if (SecurityTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRMSI ImpersonateUserChanged domain: {0}, login: {1}",domain,login),SecurityTraceSwitch.Sw.Info);
                    Owner.Settings[AStr.ImpersonateUserDomain].Value=   domain;
                    SettingItem settng                      =   Owner.Settings[AStr.ImpersonateUserLogin];
                    // force instanciate editcontrol if not already instanciated
                    settng.Value                            =   login;
                    settng                                  =   Owner.Settings[AStr.ImpersonateUserPwd];
                    settng.Value                            =   string.Empty;
                    if ( ( e.OrgDataTypeSender != null ) && ( e.OrgDataTypeSender is WSListDataType ) )
                    {
                        ((WSListDataType)e.OrgDataTypeSender).DisplayTextValue  =   user.lastname;
                    }
                }
            }
        }

        #endregion handlers for settings events

    }

    public partial class RegisterCRM : PortalCRMModuleControl
    {
        
        public const string MembershipProvider   =   "AddonNiceMembershipProvider";


        #region General implementation
        
        public override Guid GuidID
        {
            get
            {
                return new Guid("{D385E55C-D6C2-4e7f-AEFB-D1AC55806E11}");
            }
        }
        
        #endregion General implementation


        #region Ctor and Initializer

        public RegisterCRM()
        {
		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RegisterCRM Ctor BEG.",SecurityTraceSwitch.Sw.Info);

            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RegisterCRM Ctor END.",SecurityTraceSwitch.Sw.Info);
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
       			const string extgrp                     =   "REGISTERCRM";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new RegisterCRMSI(bSettings,this);
        }

        #endregion Ctor


        #region Page Load

        protected void Page_Load(object sender, EventArgs e)
        {
    		if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM Page_Load BEG at : {0}, IsPostBack: {1}",DateTime.UtcNow,Page.IsPostBack),SecurityTraceSwitch.Sw.Info);

            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM Page_Load ContinueDestinationPageUrl : '{0}'",CreateUserWizard1.ContinueDestinationPageUrl.ToString()),SecurityTraceSwitch.Sw.Info);
            if (!Page.IsPostBack)
            {
                // pop the return url
                string str                                          =   ADNPage.ReturnUrl;
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM Page_Load ReturnUrl: '{0}'.",str), PageTraceSwitch.Sw.Info);
                // and push again everything to prepare in case somebody call properties for this moduel
                ADNPage.ReturnUrl                                    =   str;
                if ( !string.IsNullOrEmpty(str) )
                {
                    if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM Page_Load set ContinueDestinationPageUrl: '{0}'.",str), PageTraceSwitch.Sw.Info);
                    CreateUserWizard1.ContinueDestinationPageUrl    =   str;
                    CreateUserWizard1.CancelDestinationPageUrl      =   str;
                    ViewState[StStr.strUrlReferrer]                 =   str;
                }

                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]RegisterCRM Page_Load Retrieving Captcha.", PageTraceSwitch.Sw.Info);
                RadCaptcha CaptchaControl1                          =   null;
                try
                {
                    CaptchaControl1                                 =   (RadCaptcha)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("RadCaptcha1");
                }
                catch (Exception ex1)
                {
                    if (SecurityTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RegisterCRM Page_Load ex: {0}", ex1),SecurityTraceSwitch.Sw.Info);
                }
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]RegisterCRM Page_Load Captcha Retrieved.", PageTraceSwitch.Sw.Info);
                if ( CaptchaControl1 != null )
                    CaptchaControl1.CaptchaTextBoxLabel             =   LocalizeHelper.Localize("CAPTCHA_TEXT", "Enter the code shown");
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]RegisterCRM Page_Load after Captcha Text set.",PageTraceSwitch.Sw.Info);
                int tpCode                                          =   Settings[AStr.CustomerType].ToInt();
    		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM Page_Load typeCode : {0}",tpCode),SecurityTraceSwitch.Sw.Info);
                switch ((ADNTypeCodes)tpCode)
                {
                    case ADNTypeCodes.Account:
                        {
                            Control ctl                         =   CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("FirstNameRow");
                            if ( ctl != null )
                                ctl.Visible                     =   false;
                        }
                        break;
                    case ADNTypeCodes.Contact:
                        {
                            // if provider manages parent acount, we display row
                            if ((Membership.Provider is AddonNiceMembershipProvider) &&
                                !((AddonNiceMembershipProvider)Membership.Provider).AutoCreateParentAccount)
                            {
                                Control ctl                     =   CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("CompanyRow");
                                if (ctl != null)
                                    ctl.Visible                 =   false;
                                ctl                             =   CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("CompanyRow2");
                                if (ctl != null)
                                    ctl.Visible                 =   false;
                            }
                        }
                        break;
                    default:
                        break;
                }
                // should we display a cancel button
                CreateUserWizard1.DisplayCancelButton               =   Settings[AStr.DisplayCancel].ToBool();
                CreateUserWizard1.ActiveStepIndex                   =   0;
                // reduced information only, we step over the first 3 pages
                if (  !Settings[AStr.MoreData].ToBool() )
                    CreateUserWizard1.ActiveStepIndex               =   3;
    		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM Page_Load ActiveStepIndex: {0}",CreateUserWizard1.ActiveStepIndex),SecurityTraceSwitch.Sw.Info);
                bool DisableCreatedUser                             =   Settings[AStr.DisableCreatedUser].ToBool();
                CreateUserWizard1.DisableCreatedUser                =   DisableCreatedUser;
                // if user is disabled don't try to log in !!!!!
                CreateUserWizard1.LoginCreatedUser                  =   DisableCreatedUser ? false : Settings[AStr.LogAfterCreate].ToBool();
                // get default country from local
                BillCountry                                         =   CountryInfo.CurrentCountry.ThreeLetterISOCountryName;
                ShipCountry                                         =   BillCountry;

				BillBindCountry();
                ShipBindCountry();
                // force label in welcome page
                CreateUserWizard1_ActiveStepChanged(this, EventArgs.Empty);
            }
    		if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM Page_Load DisableCreatedUser: {0}, LoginCreatedUser: {1}",CreateUserWizard1.DisableCreatedUser,CreateUserWizard1.LoginCreatedUser),SecurityTraceSwitch.Sw.Info);
        }
        
        #endregion Page Load


        #region buttons handlers

        void BtnResetShipping_Click(object sender, ImageClickEventArgs e)
        {
		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM BtnResetShipping_Click BEG sender: {0}",sender),SecurityTraceSwitch.Sw.Info);
            TBShippingAddress1.Text                 = string.Empty;
            TBShippingAddress2.Text                 = string.Empty;
            TBShippingAddress3.Text                 = string.Empty;
            TBShippingCity.Text                     = string.Empty;
            DDLShippingCountry.Text                 = string.Empty;
            TBShippingFax.Text                      = string.Empty;
            TBShippingPhone.Text                    = string.Empty;
            DDLShippingState.Text                   = string.Empty;
            TBShippingZip.Text                      = string.Empty;
        }


        Control FindControlDeep(Control ctrl,string strID)
        {
            if (ctrl.ID == strID )
            {
    		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM FindControlDeep found: {0}",strID),SecurityTraceSwitch.Sw.Info);
                return ctrl;
            }
            for (int i=0 ; i < ctrl.Controls.Count ; i++ ) 
            {
                Control ctrl2 = FindControlDeep(ctrl.Controls[i],strID);
                if ( ctrl2 != null )
                    return ctrl2;
            }
            return null;
        }

        void SetControlSkin(Control ctrl,string strID,string skinid)
        {
            if (ctrl.ID == strID )
            {
    		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM SetControlSkin found: {0}, skin: {1}",strID, ctrl.SkinID),SecurityTraceSwitch.Sw.Info);
                ctrl.SkinID  = skinid;
            }
            for (int i=0 ; i < ctrl.Controls.Count ; i++ ) 
            {
                SetControlSkin(ctrl.Controls[i],strID,skinid);
            }
        }

        /// <summary>
        /// Should we allow full data info entering or not
        /// </summary>
        void CreateUserWizard1_ActiveStepChanged(object sender, EventArgs e)
        {
    		if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM CreateUserWizard1_ActiveStepChanged ActiveStepIndex: {0}",CreateUserWizard1.ActiveStepIndex),SecurityTraceSwitch.Sw.Info);
            if ( CreateUserWizard1.ActiveStepIndex == 2 )
            {
                if (CBCopyBilling.Checked)
                {
                    TBShippingAddress1.Text =   TBBillingAddress1.Text;
                    TBShippingAddress2.Text =   TBBillingAddress2.Text;
                    TBShippingAddress3.Text =   TBBillingAddress3.Text;
                    TBShippingCity.Text     =   TBBillingCity.Text;
                    DDLShippingCountry.Text =   DDLBillingCountry.Text;
                    TBShippingFax.Text      =   TBBillingFax.Text;
                    TBShippingPhone.Text    =   TBBillingPhone.Text;
                    TBShippingZip.Text      =   TBBillingZip.Text;
                    ShipCountry             =   BillCountry;
                    if ( DDLBillingState.SelectedIndex != -1 )
                        ShipState           =   DDLBillingState.SelectedValue;
                    ShipBindCountry();
                }
            }

            Label lbl   =   (Label)FindControlDeep(CreateUserWizard1,"HeaderLbl");
    		if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM CreateUserWizard1_ActiveStepChanged lbl == null: {0}",lbl == null),SecurityTraceSwitch.Sw.Info);
            if ( lbl != null )
                switch (CreateUserWizard1.ActiveStepIndex)
                {
                    case 0: //welcome
                        lbl.Text    =   LocalizeHelper.Localize("REGISTERCRM_WELCOME","New account creation");
                        break;
                    case 1: // billing
                        {
                            Control ctl     = (Label)FindControlDeep(CreateUserWizard1,"MoveNextBtn");
                            if ((ctl != null) && (ctl is ImageButton))
                            {
                                ((ImageButton)ctl).CausesValidation = true;
                                ((ImageButton)ctl).ValidationGroup = "Billing";
                            }
                            lbl.Text    =   LocalizeHelper.Localize(AStr.BillingInfo,"Billing Information");
                            break;
                        }
                    case 2: // shipping
                        {
                            Control ctl     = (Label)FindControlDeep(CreateUserWizard1,"MoveNextBtn");
                            if ((ctl != null) && (ctl is ImageButton))
                            {
                                ((ImageButton)ctl).CausesValidation = true;
                                ((ImageButton)ctl).ValidationGroup = "Shipping";
                            }
                            lbl.Text    =   LocalizeHelper.Localize(AStr.ShippingInfo,"Shipping Information");
                            break;
                        }
                    case 3: // createuser
                        lbl.Text    =   LocalizeHelper.Localize("REGISTERCRM_CREATEUSER","Create Account");
                        break;
                    case 4: // done
                        lbl.Text    =   LocalizeHelper.Localize("REGISTERCRM_END","Create terminated");
                        break;
                }
        }

        protected void CreateUserWizard1_CreatingUser(object sender, LoginCancelEventArgs e)
        {
    		if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RegisterCRM CreateUserWizard1_CreatingUser BEG.",SecurityTraceSwitch.Sw.Info);
            // First check the Capcha
            RadCaptcha CaptchaControl1      =   (RadCaptcha)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("RadCaptcha1");
            if ( CaptchaControl1 == null || !CaptchaControl1.IsValid )
            {
                e.Cancel                    =   true;
                Literal ErrorMessage        =   (Literal)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("ErrorMessage");
                if ( ErrorMessage != null )
                    ErrorMessage.Text       =   LocalizeHelper.Localize("REGISTERCRM_INVALIDCAPTCHA","Invalid confirmation string, retry.");
                return;
            }
            Guid CrmImpersonateID                   =   new Guid(Settings[AStr.ImpersonateUser].Value);
            string CrmImpersonateDomain             =   Settings[AStr.ImpersonateUserDomain].Value;
            string CrmImpersonateLogin              =   Settings[AStr.ImpersonateUserLogin].Value;
            string CrmImpersonatePwd                =   Settings[AStr.ImpersonateUserPwd].Value;
            int tpCode                              =   Settings[AStr.CustomerType].ToInt();
    		if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM CreateUserWizard1_CreatingUser CrmImpersonateID: {0}, tpCode: {1}, Domain: {2}, Login: {3}.",
                    new object[]{CrmImpersonateID, tpCode,CrmImpersonateDomain,CrmImpersonateLogin}),SecurityTraceSwitch.Sw.Info);
            Context.Items["CrmTypeCode"]            =   tpCode;
            Context.Items["CrmImpersonateId"]       =   CrmImpersonateID;
            Context.Items["CrmImpersonateDomain"]   =   CrmImpersonateDomain;
            Context.Items["CrmImpersonateLogin"]    =   CrmImpersonateLogin;
            Context.Items["CrmImpersonatePwd"]      =   CrmImpersonatePwd;
            Context.Items["CrmIsCrmUser"]           =   false;

    		if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RegisterCRM CreateUserWizard1_CreatingUser END.",SecurityTraceSwitch.Sw.Info);
        }


        protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
        {
    		if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RegisterCRM CreateUserWizard1_CreatedUser BEG.",SecurityTraceSwitch.Sw.Info);
            string frmt                     =   LocalizeHelper.Localize("REGISTERCRM_WELCOMECRATED","{0}, thanks for creating an account with us.");
            CreateUserWizard1.CompleteSuccessText = String.Format(frmt,Context.User.Identity.Name);
            Label lbl                       =   (Label)FindControlDeep(CreateUserWizard1,"CompleteLbl");
            if ( lbl != null )
                lbl.Text                    =   CreateUserWizard1.CompleteSuccessText ;

            bool createAll                  =   Settings[AStr.MoreData].ToBool();
            bool addToProfile               =   Settings[AStr.AddToProfile].ToBool();
    		if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM CreateUserWizard1_CreatedUser createAll: {0}, addToProfile: {1}",createAll,addToProfile),SecurityTraceSwitch.Sw.Info);
            // should we add to profile
            HttpContext context             =   HttpContext.Current;
            AddonNiceMembershipUser usr     =   (AddonNiceMembershipUser)Membership.GetUser(CreateUserWizard1.UserName);
            usr.EnsureCrmDataLoaded();
            if (addToProfile)
            {
                try
                {
                    //context.Profile.UserName = CreateUserWizard1.UserName;
                    if (SecurityTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine("[V]RegisterCRM CreateUserWizard1_CreatedUser addToProfile EMail",SecurityTraceSwitch.Sw.Info);
                    context.Profile.SetPropertyValue("EMail", CreateUserWizard1.Email);
                    if (SecurityTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine("[V]RegisterCRM CreateUserWizard1_CreatedUser addToProfile typeCode",SecurityTraceSwitch.Sw.Info);
                    context.Profile.SetPropertyValue("typeCode", usr.typeCode);
                    if (SecurityTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine("[V]RegisterCRM CreateUserWizard1_CreatedUser addToProfile CrmId",SecurityTraceSwitch.Sw.Info);
                    context.Profile.SetPropertyValue("CrmId", usr.CustomerId.CrmId);
                    if (SecurityTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine("[V]RegisterCRM CreateUserWizard1_CreatedUser addToProfile CrmImpersonateId",SecurityTraceSwitch.Sw.Info);
                    context.Profile.SetPropertyValue("CrmImpersonateId", usr.CrmImpersonateId);
                    if (SecurityTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine("[V]RegisterCRM CreateUserWizard1_CreatedUser addToProfile BillingCountry",SecurityTraceSwitch.Sw.Info);
                    context.Profile.SetPropertyValue("BillingCountry", usr.BillCountry);
                }
                catch (Exception ex1)
                {
                    if (SecurityTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RegisterCRM CreateUserWizard1_CreatedUser addToProfile userName: {0}, ex: {1}", CreateUserWizard1.UserName, ex1),SecurityTraceSwitch.Sw.Info);
                }
            }
            // Empties context from temp values
            Context.Items.Remove("CrmTypeCode");
            Context.Items.Remove("CrmImpersonateId");
            Context.Items.Remove("CrmImpersonateDomain");
            Context.Items.Remove("CrmImpersonateLogin");
            Context.Items.Remove("CrmImpersonatePwd");
            Context.Items.Remove("CrmIsCrmUser");
            if ( !createAll )
                return;
            TextBox tb                  =   (TextBox)CreateUserWizardStep1.ContentTemplateContainer.FindControl("TBCompany");
            if ( tb != null )
                usr.Company             =   tb.Text.Trim();
            tb                          =   (TextBox)CreateUserWizardStep1.ContentTemplateContainer.FindControl("TBSic");
            if ( tb != null )
                usr.SIC                 =   tb.Text.Trim();
            tb                          =   (TextBox)CreateUserWizardStep1.ContentTemplateContainer.FindControl("TBFirstName");
            if ( tb != null )
                usr.UserFirstName       =   tb.Text.Trim();
            tb                          =   (TextBox)CreateUserWizardStep1.ContentTemplateContainer.FindControl("TBNickname");
            if ( tb != null )
                usr.nickname            =   tb.Text.Trim();
            CheckBox cbx                =   (CheckBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("CheckBoxSendNewsletter");
            if ( cbx != null )
                usr.SendNewsletter      =   cbx.Checked;

            usr.BillAddress1            =   TBBillingAddress1.Text.Trim();
            usr.BillAddress2            =   TBBillingAddress2.Text.Trim();
            usr.BillAddress3            =   TBBillingAddress3.Text.Trim();
            usr.BillCity                =   TBBillingCity.Text.Trim();
            
            usr.BillCountry             =   DDLBillingCountry.SelectedItem.Text;
            usr.BillFax                 =   TBBillingFax.Text.Trim();
            usr.BillPhone               =   TBBillingPhone.Text.Trim();
            usr.BillCounty              =   DDLBillingState.SelectedValue;
            usr.BillZip                 =   TBBillingZip.Text.Trim();


            usr.ShipAddress1            =   TBShippingAddress1.Text.Trim();
            usr.ShipAddress2            =   TBShippingAddress2.Text.Trim();
            usr.ShipAddress3            =   TBShippingAddress3.Text.Trim();
            usr.ShipCity                =   TBShippingCity.Text.Trim();
            
            usr.ShipCountry             =   DDLShippingCountry.SelectedItem.Text;
            usr.ShipFax                 =   TBShippingFax.Text.Trim();
            usr.ShipPhone               =   TBShippingPhone.Text.Trim();
            usr.ShipCounty              =   DDLShippingState.SelectedValue;
            usr.ShipZip                 =   TBShippingZip.Text.Trim();
            try
            {
    		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM CreateUserWizard1_CreatedUser before UpdateCrmData userName: {0}",CreateUserWizard1.UserName),SecurityTraceSwitch.Sw.Info);
                usr.UpdateCrmData();
    		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM CreateUserWizard1_CreatedUser UpdateCrmData userName: {0}, Ok",CreateUserWizard1.UserName),SecurityTraceSwitch.Sw.Info);
            }
            catch (Exception ex)
            {
    		    if (SecurityTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RegisterCRM CreateUserWizard1_CreatedUser UpdateCrmData userName: {0}, ex: {1}",CreateUserWizard1.UserName, ex),SecurityTraceSwitch.Sw.Info);
                throw;
            }
    		if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RegisterCRM CreateUserWizard1_CreatedUser END.",SecurityTraceSwitch.Sw.Info);
        }

        #endregion

        #region State and Country
        
        private string BillCountry
        {
            get
            {
                if (ViewState["BCtr"] != null)
                    return (string)ViewState["BCtr"];
                return string.Empty;
            }
            set
            {
                ViewState["BCtr"] = value;
            }
        }

        private string BillState
        {
            get
            {
                if (ViewState["BSte"] != null)
                    return (string)ViewState["BSte"];
                return string.Empty;
            }
            set
            {
                ViewState["BSte"] = value;
            }
        }

        private string ShipCountry
        {
            get
            {
                if (ViewState["SCtr"] != null)
                    return (string)ViewState["SCtr"];
                return string.Empty;
            }
            set
            {
                ViewState["SCtr"] = value;
            }
        }

        private string ShipState
        {
            get
            {
                if (ViewState["SSte"] != null)
                    return (string)ViewState["SSte"];
                return string.Empty;
            }
            set
            {
                ViewState["SSte"] = value;
            }
        }

        protected void DDLBillingCountry_SelectedIndexChanged(object sender, System.EventArgs e) 
        {
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM DDLBillingCountry_SelectedIndexChanged SelectedItem null: {0}, DDLBillingCountry.Items.Count: {1}", DDLBillingCountry.SelectedItem == null,DDLBillingCountry.Items.Count),SecurityTraceSwitch.Sw.Info);
            try 
            {
                BillCountry             =   DDLBillingCountry.SelectedItem.Value;
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM DDLBillingCountry_SelectedIndexChanged BillCountry: {0}", BillCountry),SecurityTraceSwitch.Sw.Info);
                BillState               =   string.Empty;
                DDLBillingState.Items.Clear();
                BillBindState();
            } 
            catch (Exception exp) 
            {
                if (SecurityTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RegisterCRM DDLBillingCountry_SelectedIndexChanged ex: {0}", exp),SecurityTraceSwitch.Sw.Info);
            }
        }

        protected void DDLShippingCountry_SelectedIndexChanged(object sender, System.EventArgs e) 
        {
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM DDLShippingCountry_SelectedIndexChanged SelectedItem null: {0}", DDLShippingCountry.SelectedItem == null),SecurityTraceSwitch.Sw.Info);
            try 
            {
                ShipCountry             =   DDLShippingCountry.SelectedItem.Value;
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM DDLShippingCountry_SelectedIndexChanged ShipCountry: {0}", ShipCountry),SecurityTraceSwitch.Sw.Info);
                ShipState               =   string.Empty;
                DDLShippingState.Items.Clear();
                ShipBindState();
            } 
            catch (Exception exp) 
            {
                if (SecurityTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RegisterCRM SDDLBillingCountry_SelectedIndexChanged ex: {0}", exp),SecurityTraceSwitch.Sw.Info);
                throw;
            }

        }

        private void BillBindCountry() 
        {
            try 
            {
                //Country filter limits country list
                string CountriesFilter              =   portalSettings.CustomSettings[StStr.SiteSettingsCountryFilter].ToString();
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM BillBindCountry CountriesFilter: [{0}]", CountriesFilter),SecurityTraceSwitch.Sw.Info);
                DDLBillingCountry.DataTextField     =   "DisplayName";
                DDLBillingCountry.DataValueField    =   "ThreeLetterISOCountryName";
 				if ( CountriesFilter != string.Empty )
				{
					DDLBillingCountry.DataSource    =   CountryInfo.GetCountries(CountriesFilter,CountryFields.DisplayName);
				}
				else
				{
					DDLBillingCountry.DataSource    =   CountryInfo.GetCountries(CountryTypes.InhabitedCountries,CountryFields.DisplayName);
				}
                DDLBillingCountry.DataBind();
                DDLBillingState.Items.Clear();
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM BillBindCountry DDLBillingCountry.Items.Count : {0}", DDLBillingCountry.Items.Count ),SecurityTraceSwitch.Sw.Info);
                if ( DDLBillingCountry.Items.Count > 0)
                {
                    if (string.IsNullOrEmpty(BillCountry))
                    {
                        BillCountry = DDLBillingCountry.Items[0].Value;
                        if (SecurityTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM BillBindCountry BillCountry: {0}", BillCountry), SecurityTraceSwitch.Sw.Info);
                    }
                    DDLBillingCountry.SelectedValue = BillCountry;
                        if (SecurityTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM BillBindCountry DDLBillingCountry.SelectedIndex: {0}", DDLBillingCountry.SelectedIndex), SecurityTraceSwitch.Sw.Info);
                    BillBindState();
                }
            } 
            catch (Exception exp) 
            {
                if (SecurityTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RegisterCrm BillBindCountry ex: {0}", exp),SecurityTraceSwitch.Sw.Info);
                throw;
            }
        }

        private void BillBindState() 
        {
            BillBindState2();
        }

        private void BillBindState2() 
        {
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM BillBindState BillState: '{0}'", BillState),SecurityTraceSwitch.Sw.Info);
            DDLBillingState.DataTextField       =   "EnglishName";
            DDLBillingState.DataValueField      =   "EnglishName";
            try 
            {
                string currentCountry           =   BillCountry;
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM BillBindState currentCountry: {0}", currentCountry),SecurityTraceSwitch.Sw.Info);
                if (!string.IsNullOrEmpty(currentCountry)) 
                {
                    DDLBillingState.DataSource	=	new CountryInfo(currentCountry).Childs;
                    DDLBillingState.DataBind();
                    if (SecurityTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM BillBindState DDLBillingState.Items.Count: {0}", DDLBillingState.Items.Count),SecurityTraceSwitch.Sw.Info);
                    if (DDLBillingState.Items.Count > 0) 
                    {
                        if (string.IsNullOrEmpty(BillState))
                        {
                            BillState    =   DDLBillingState.Items[0].Value;
                        }
                        if (SecurityTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM BillBindState BillState: '{0}'", BillState),SecurityTraceSwitch.Sw.Info);
                        DDLBillingState.SelectedValue   =   BillState;
                    }
                }
            } 
            catch (Exception exp) 
            {
                if (SecurityTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RegisterCRM BindState ex: {0}", exp),SecurityTraceSwitch.Sw.Info);
                throw;
            }
        }

        private void ShipBindCountry() 
        {
            DDLShippingCountry.DataTextField            =   "DisplayName";
            DDLShippingCountry.DataValueField           =   "ThreeLetterISOCountryName";
            try 
            {
                //Country filter limits country list
                string CountriesFilter                  =   portalSettings.CustomSettings[StStr.SiteSettingsCountryFilter].ToString();
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM ShipBindCountry CountriesFilter: '{0}'", CountriesFilter),SecurityTraceSwitch.Sw.Info);
				if ( CountriesFilter != string.Empty )
				{
					DDLShippingCountry.DataSource       =   CountryInfo.GetCountries(CountriesFilter,CountryFields.DisplayName);
				}
				else
				{
					DDLShippingCountry.DataSource	    =   CountryInfo.GetCountries(CountryTypes.InhabitedCountries,CountryFields.DisplayName);
				}
                DDLShippingCountry.DataBind();
                DDLShippingState.Items.Clear();
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM ShipBindCountry DDLShippingCountry.Items.Count: {0}", DDLShippingCountry.Items.Count),SecurityTraceSwitch.Sw.Info);
                if (DDLShippingCountry.Items.Count > 0)
                {
                    if (string.IsNullOrEmpty(ShipCountry) )
                    {
                        ShipCountry                     =   DDLShippingCountry.Items[0].Value;
                        if (SecurityTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM ShipBindCountry set ShipCountry: {0}", ShipCountry),SecurityTraceSwitch.Sw.Info);
                    }
                    if (SecurityTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM ShipBindCountry ShipCountry: [{0}]", ShipCountry),SecurityTraceSwitch.Sw.Info);
                    DDLShippingCountry.SelectedValue    =   ShipCountry;
                    if (SecurityTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM ShipBindCountry DDLShippingCountry.Text : {0}", DDLShippingCountry.Text), SecurityTraceSwitch.Sw.Info);
                    ShipBindState();
                }
            } 
            catch (Exception exp) 
            {
                if (SecurityTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RegisterCRM ShipBindCountry ex: {0}", exp),SecurityTraceSwitch.Sw.Info);
                throw;
            }
        }

        private void ShipBindState() 
        {
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM ShipBindState BEG ShipState: '{0}'", ShipState),SecurityTraceSwitch.Sw.Info);
            if (ShipState == string.Empty) 
            {
                if (ShipCountry == BillCountry) 
                {
                    if (DDLBillingState.SelectedItem != null)
                        ShipState       =   DDLBillingState.SelectedItem.Value;
                }
            }
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM ShipBindState END ShipState: '{0}'", ShipState),SecurityTraceSwitch.Sw.Info);
            ShipBindState2();
        }

        private void ShipBindState2() 
        {
            DDLShippingState.DataTextField          =   "EnglishName";
            DDLShippingState.DataValueField         =   "EnglishName";
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM ShipBindState BEG ShipState: '{0}'", ShipState),SecurityTraceSwitch.Sw.Info);
            try 
            {
                string currentShipCountry           =   ShipCountry;
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM ShipBindState currentShipCountry: '{0}'", currentShipCountry),SecurityTraceSwitch.Sw.Info);
                if ( !string.IsNullOrEmpty(currentShipCountry) ) 
                {
                    if (SecurityTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM ShipBindState DDLShippingState.Items.Count: {0}", DDLShippingState.Items.Count),SecurityTraceSwitch.Sw.Info);
					DDLShippingState.DataSource		=	new CountryInfo(currentShipCountry).Childs;
                    DDLShippingState.DataBind();
                    if (SecurityTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM ShipBindState DDLShippingState.Items.Count: {0}", DDLShippingState.Items.Count),SecurityTraceSwitch.Sw.Info);
                    if (DDLShippingState.Items.Count > 0) 
                    {
                        if (string.IsNullOrEmpty(ShipState))
                        {
                            ShipState               =   DDLShippingState.Items[0].Value;
                        }
                        if (SecurityTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM ShipBindState ShipState: {0}", ShipState),SecurityTraceSwitch.Sw.Info);
                        DDLShippingState.SelectedValue  =   ShipState;
                    }
                }
            } 
            catch (Exception exp) 
            {
                if (SecurityTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RegisterCRM BindState ex: {0}", exp),SecurityTraceSwitch.Sw.Info);
                throw;
            }
        }

        #endregion
        
        #region Std overrides
        internal class StartNavigationTemplate : ITemplate 
        {
            CreateUserWizard _owner =   null;
            public StartNavigationTemplate(CreateUserWizard owner)
            {
                _owner   =   owner;
            }

            void ITemplate.InstantiateIn(Control ctl)
            {
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM StartNavigationTemplate InstantiateIn BEG : {0}.",ctl),SecurityTraceSwitch.Sw.Info);
                string ext              =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
                Table tb                =   new Table();
                tb.CellPadding          =   0;
                tb.CellSpacing          =   2;
                TableRow rw             =   new TableRow();
                rw.HorizontalAlign      =   HorizontalAlign.Center;
                TableCell c             =   new TableCell();
                ImageButton cancelBtn   =   new ImageButton();
                cancelBtn.ID            =   "StartCancelButton";
                cancelBtn.CommandName   =   "Cancel";
                cancelBtn.SkinID        =   "cancel_"+ext;
                cancelBtn.CausesValidation  = false;
                cancelBtn.AlternateText =   LocalizeHelper.Localize("CANCEL","cancelBtn");
                c.Controls.Add(cancelBtn);
                rw.Cells.Add(c);
                c                       =   new TableCell();
                ImageButton nextBtn     =   new ImageButton();
                nextBtn.ID              =   "StartNextButton";
                nextBtn.CommandName     =   "MoveNext";
                nextBtn.SkinID          =   "setupnext_" + ext;
                nextBtn.CausesValidation= false;
                nextBtn.AlternateText   =   LocalizeHelper.Localize("REGISTERCRM_WIZARD_STARTNEXT","Next");
                c.Controls.Add(nextBtn);
                rw.Cells.Add(c);
                tb.Rows.Add(rw);
                ctl.Controls.Add(tb);
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]RegisterCRM StartNavigationTemplate InstantiateIn END.",SecurityTraceSwitch.Sw.Info);
            }
        }
        
        internal class StepNavigationTemplate : ITemplate 
        {
            CreateUserWizard _owner =   null;
            public StepNavigationTemplate(CreateUserWizard owner)
            {
                _owner   =   owner;
            }
            void ITemplate.InstantiateIn(Control ctl)
            {
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM StepNavigationTemplate InstantiateIn BEG : {0}.",ctl),SecurityTraceSwitch.Sw.Info);
                string ext              =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
                Table tb                =   new Table();
                tb.CellPadding          =   0;
                tb.CellSpacing          =   2;
                TableRow rw             =   new TableRow();
                rw.HorizontalAlign      =   HorizontalAlign.Center;
                TableCell c             =   new TableCell();
                ImageButton cancelBtn   =   new ImageButton();
                cancelBtn.ID            =   "StepCancelButton";
                cancelBtn.CommandName   =   "Cancel";
                cancelBtn.SkinID        =   "cancel_"+ext;
                cancelBtn.CausesValidation  = false;
                cancelBtn.AlternateText =   LocalizeHelper.Localize("CANCEL","cancelBtn");
                c.Controls.Add(cancelBtn);
                rw.Cells.Add(c);
                c                       =   new TableCell();
                ImageButton prevBtn     =   new ImageButton();
                prevBtn.ID              =   "StepPreviousButton";
                prevBtn.CommandName     =   "MovePrevious";
                prevBtn.SkinID          =   "adn_previous_" + ext;
                prevBtn.CausesValidation= false;
                prevBtn.AlternateText   =   LocalizeHelper.Localize("REGISTERCRM_WIZARD_PREV","Next");
                c.Controls.Add(prevBtn);
                rw.Cells.Add(c);
                c                       =   new TableCell();
                ImageButton nextBtn     =   new ImageButton();
                nextBtn.ID              =   "StepNextButton";
                nextBtn.CommandName     =   "MoveNext";
                nextBtn.SkinID          =   "setupnext_" + ext;
                nextBtn.CausesValidation= true;
                nextBtn.ValidationGroup =   "StepValidation";
                nextBtn.AlternateText   =   LocalizeHelper.Localize("REGISTERCRM_WIZARD_STARTNEXT","Next");
                c.Controls.Add(nextBtn);
                rw.Cells.Add(c);
                tb.Rows.Add(rw);
                ctl.Controls.Add(tb);
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]RegisterCRM StepNavigationTemplate InstantiateIn END.",SecurityTraceSwitch.Sw.Info);
            }
        }

        internal class CustomNavigationTemplate : ITemplate 
        {
            CreateUserWizard _owner =   null;
            public CustomNavigationTemplate(CreateUserWizard owner)
            {
                _owner   =   owner;
            }
            void ITemplate.InstantiateIn(Control ctl)
            {
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM CustomNavigationTemplate InstantiateIn BEG : {0}.",ctl),SecurityTraceSwitch.Sw.Info);
                string ext              =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
                Table tb                =   new Table();
                tb.CellPadding          =   0;
                tb.CellSpacing          =   2;
                TableRow rw             =   new TableRow();
                rw.HorizontalAlign      =   HorizontalAlign.Center;
                TableCell c             =   new TableCell();
                ImageButton cancelBtn   =   new ImageButton();
                cancelBtn.ID            =   "CreateUserCancelButton";
                cancelBtn.CommandName   =   CreateUserWizard.CancelCommandName;//"Cancel";
                cancelBtn.SkinID        =   "cancel_"+ext;
                cancelBtn.CausesValidation  = false;
                cancelBtn.AlternateText =   LocalizeHelper.Localize("CANCEL","cancelBtn");
                c.Controls.Add(cancelBtn);
                rw.Cells.Add(c);
                c                       =   new TableCell();
                ImageButton prevBtn     =   new ImageButton();
                prevBtn.ID              =   "CreateUserPreviousButton";
                prevBtn.CommandName     =   CreateUserWizard.MovePreviousCommandName;//"MovePrevious";
                prevBtn.SkinID          =   "adn_previous_" + ext;
                prevBtn.CausesValidation= false;
                prevBtn.AlternateText   =   LocalizeHelper.Localize("REGISTERCRM_WIZARD_PREV","Next");
                c.Controls.Add(prevBtn);
                rw.Cells.Add(c);
                c                       =   new TableCell();
                ImageButton nextBtn     =   new ImageButton();
                nextBtn.ID              =   "CreateUserButton";
                nextBtn.CommandName     =   CreateUserWizard.MoveNextCommandName;//"MoveNext";
                nextBtn.SkinID          =   "adn_createuser_" + ext;
                nextBtn.CausesValidation= true;
                nextBtn.ValidationGroup =   "CreateUserWizardStep1";
                nextBtn.AlternateText   =   LocalizeHelper.Localize("REGISTERCRM_WIZARD_STARTNEXT","Next");
                c.Controls.Add(nextBtn);
                rw.Cells.Add(c);
                tb.Rows.Add(rw);
                ctl.Controls.Add(tb);
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]RegisterCRM CustomNavigationTemplate InstantiateIn END.",SecurityTraceSwitch.Sw.Info);
            }
        }
        
        internal class CompleteNavigationTemplate : ITemplate 
        {
            CreateUserWizard _owner =   null;
            public CompleteNavigationTemplate(CreateUserWizard owner)
            {
                _owner                      =   owner;
            }
            void ITemplate.InstantiateIn(Control ctl)
            {
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM CompleteNavigationTemplate InstantiateIn BEG : {0}.",ctl),SecurityTraceSwitch.Sw.Info);
                string ext                  =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
                Table tb                    =   new Table();
                tb.CellPadding              =   0;
                tb.CellSpacing              =   2;
                TableRow rw                 =   new TableRow();
                rw.HorizontalAlign          =   HorizontalAlign.Center;
                TableCell c                 =   new TableCell();
                ImageButton continueBtn     =   new ImageButton();
                continueBtn.ID              =   "ContinueButton";
                continueBtn.CommandName     =   "Continue";
                continueBtn.SkinID          =   "continue_"+ext;
                continueBtn.CausesValidation  = false;
                continueBtn.AlternateText   =   LocalizeHelper.Localize("CONTINUE","Continue");
                c.Controls.Add(continueBtn);
                rw.Cells.Add(c);
                tb.Rows.Add(rw);
                ctl.Controls.Add(tb);
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]RegisterCRM CompleteNavigationTemplate InstantiateIn END.",SecurityTraceSwitch.Sw.Info);
            }
        }

        public override void Page_PreInit(object sender, EventArgs e)
        {
 		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RegisterCRM Page_PreInit BEG.",SecurityTraceSwitch.Sw.Info);
            base.Page_PreInit(sender, e);
            string ext                                                  =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            BtnResetShipping.SkinID                                     =   "Reset_" + ext;
            CreateUserWizard1.StartNavigationTemplate                   =   new StartNavigationTemplate(CreateUserWizard1);
            CreateUserWizard1.StepNavigationTemplate                    =   new StepNavigationTemplate(CreateUserWizard1);
            ((TemplatedWizardStep)CreateUserWizard1.WizardSteps[3]).CustomNavigationTemplate=new CustomNavigationTemplate(CreateUserWizard1);
            ((TemplatedWizardStep)CreateUserWizard1.WizardSteps[4]).CustomNavigationTemplate=new CompleteNavigationTemplate(CreateUserWizard1);

  		    //if (SecurityTraceSwitch.Sw.TraceVerbose)
            //    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM Page_PreInit before MembershipProvider ChildCreated: {0}.",CreateUserWizard1.ChildCreated()),SecurityTraceSwitch.Sw.Info);
            if ( string.IsNullOrEmpty(CreateUserWizard1.MembershipProvider) || CreateUserWizard1.MembershipProvider != AddonNiceMembershipProvider.ProviderClassName )
                CreateUserWizard1.MembershipProvider =   AddonNiceMembershipProvider.ProviderClassName;

            //if (SecurityTraceSwitch.Sw.TraceVerbose)
            //    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM Page_PreInit WizardSteps.Count: {0}, ChildCreated: {1}.", CreateUserWizard1.WizardSteps.Count,CreateUserWizard1.ChildCreated()), SecurityTraceSwitch.Sw.Info);
            Control ctl                                             =   CreateUserWizard1.WizardSteps[0].FindControl("ReadConditions");
            bool bfound                                             =   (ctl != null) && (ctl is HyperLink);
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM Page_PreInit ReadConditions found: {0}.", bfound), SecurityTraceSwitch.Sw.Info);
            if ( bfound )
            {
                // TermsOfService:
                int PgID                            =   portalSettings.CustomSettings[StStr.SiteTermsOfService].ToInt();
                ((HyperLink)ctl).NavigateUrl        =   HttpUrlBuilder.BuildUrl(PgID);
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM Page_PreInit ReadConditions: {0}.", ((HyperLink)ctl).NavigateUrl), SecurityTraceSwitch.Sw.Info);
            }
 
            CreateUserWizard1.EditProfileUrl        =   HttpUrlBuilder.BuildUrl("~/editprofile.aspx",true,DynPageLoc.Secured,StStr.PageEditProfileID);
            //ctl                                     =   CreateUserWizard1.CompleteStep.ContentTemplateContainer.FindControl("EditProfileLinkSuccess");
            ctl                                     =   CreateUserWizard1.WizardSteps[4].FindControl("EditProfileLinkSuccess");
            
            bfound                                  =   (ctl != null) && (ctl is HyperLink);
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM Page_PreInit EditProfileLinkSuccess found: {0}.", bfound), SecurityTraceSwitch.Sw.Info);
            if ( bfound )
            {
                // EditProfile:
                ((HyperLink)ctl).NavigateUrl        =   HttpUrlBuilder.BuildUrl("~/editprofile.aspx",true,DynPageLoc.Secured,StStr.PageEditProfileID);
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM Page_PreInit EditProfileLinkSuccess: {0}.", ((HyperLink)ctl).NavigateUrl), SecurityTraceSwitch.Sw.Info);
            }
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RegisterCRM Page_PreInit templates created.", SecurityTraceSwitch.Sw.Info);

 		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RegisterCRM Page_PreInit END.",SecurityTraceSwitch.Sw.Info);
        }


        override protected void OnInit(EventArgs e)
        {
 		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RegisterCRM OnInit BEG.",SecurityTraceSwitch.Sw.Info);
            InitializeComponent();
 		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RegisterCRM OnInit calling base.OnInit.",SecurityTraceSwitch.Sw.Info);
            base.OnInit(e);
 		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RegisterCRM OnInit END.",SecurityTraceSwitch.Sw.Info);
        }

        private void InitializeComponent()
        {
 		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RegisterCRM InitializeComponent BEG.",SecurityTraceSwitch.Sw.Info);
            Load                                    +=  new System.EventHandler(Page_Load);
 		    //if (SecurityTraceSwitch.Sw.TraceVerbose)
            //    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM InitializeComponent before CreatingUser ChildCreated: {0}.",CreateUserWizard1.ChildCreated()),SecurityTraceSwitch.Sw.Info);
            CreateUserWizard1.CreatingUser          +=  new LoginCancelEventHandler(CreateUserWizard1_CreatingUser);
 		    if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RegisterCRM InitializeComponent before CreatedUser.",SecurityTraceSwitch.Sw.Info);
            CreateUserWizard1.CreatedUser           +=  new EventHandler(CreateUserWizard1_CreatedUser);
 		    //if (SecurityTraceSwitch.Sw.TraceVerbose)
            //    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM InitializeComponent before ActiveStepChanged ChildCreated: {0}.",CreateUserWizard1.ChildCreated()),SecurityTraceSwitch.Sw.Info);
            CreateUserWizard1.ActiveStepChanged     +=  new EventHandler(CreateUserWizard1_ActiveStepChanged);  
            DDLBillingCountry.SelectedIndexChanged  +=  new EventHandler(DDLBillingCountry_SelectedIndexChanged);
            DDLShippingCountry.SelectedIndexChanged +=  new EventHandler(DDLShippingCountry_SelectedIndexChanged);
            BtnResetShipping.Click                  +=  new ImageClickEventHandler(BtnResetShipping_Click);
            string ext                              =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
 		    //if (SecurityTraceSwitch.Sw.TraceVerbose)
            //    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM InitializeComponent before FindControl ChildCreated: {0}.",CreateUserWizard1.ChildCreated()),SecurityTraceSwitch.Sw.Info);
            
            Control ctl                             =   null;
            try
            {
                ctl                                 =   CreateUserWizard1.CreateUserStep.CustomNavigationTemplateContainer.FindControl("CreateUserButton");
            }
            catch(Exception ex)
            {
                if (SecurityTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RegisterCRM InitializeComponent ex: {0}.", ex), SecurityTraceSwitch.Sw.Info);
            }
            bool bfound                             =   (ctl != null) && (ctl is ImageButton);
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM InitializeComponent CreateUserButton found: {0}.", bfound), SecurityTraceSwitch.Sw.Info);
            if ( bfound )
            {
                ((ImageButton)ctl).CommandName      =   CreateUserWizard.MoveNextCommandName;
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM InitializeComponent ContinueButtonCommandName: {0}, skin: {1}.", CreateUserWizard.MoveNextCommandName,ctl.SkinID), SecurityTraceSwitch.Sw.Info);
            }
            ctl                                     =   CreateUserWizard1.CreateUserStep.CustomNavigationTemplateContainer.FindControl("CreateUserCancelButton");
            bfound                                  =   (ctl != null) && (ctl is ImageButton);
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM InitializeComponent CreateUserCancelButton found: {0}.", bfound), SecurityTraceSwitch.Sw.Info);
            if ( bfound )
            {
                ((ImageButton)ctl).CommandName      =   CreateUserWizard.CancelCommandName;
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM InitializeComponent CancelCommandName: {0}.", CreateUserWizard.CancelCommandName), SecurityTraceSwitch.Sw.Info);
            }
            ctl                                     =   CreateUserWizard1.CreateUserStep.CustomNavigationTemplateContainer.FindControl("CreateUserPreviousButton");
            bfound                                  =   (ctl != null) && (ctl is ImageButton);
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM InitializeComponent CreateUserPreviousButton found: {0}.", bfound), SecurityTraceSwitch.Sw.Info);
            if ( bfound )
            {
                ((ImageButton)ctl).CommandName      =   CreateUserWizard.MovePreviousCommandName;
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM InitializeComponent MovePreviousCommandName: {0}.", CreateUserWizard.MoveNextCommandName), SecurityTraceSwitch.Sw.Info);
            }
            
            /*
            Control ctl                                     =   CreateUserWizard1.WizardSteps[0].FindControl("ReadConditions");
            bool bfound                                  =   (ctl != null) && (ctl is HyperLink);
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM InitializeComponent ReadConditions found: {0}.", bfound), SecurityTraceSwitch.Sw.Info);
            if ( bfound )
            {
                // TermsOfService:
                int PgID                            =   portalSettings.CustomSettings[StStr.SiteTermsOfService].ToInt();
                ((HyperLink)ctl).NavigateUrl        =   HttpUrlBuilder.BuildUrl(PgID);
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM InitializeComponent ReadConditions: {0}.", ((HyperLink)ctl).NavigateUrl), SecurityTraceSwitch.Sw.Info);
            }
 
            CreateUserWizard1.EditProfileUrl        =   HttpUrlBuilder.BuildUrl("~/editprofile.aspx",true,DynPageLoc.Secured,StStr.PageEditProfileID);
            ctl                                     =   CreateUserWizard1.CompleteStep.ContentTemplateContainer.FindControl("EditProfileLinkSuccess");
            bfound                                  =   (ctl != null) && (ctl is HyperLink);
            if (SecurityTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM InitializeComponent EditProfileLinkSuccess found: {0}.", bfound), SecurityTraceSwitch.Sw.Info);
            if ( bfound )
            {
                // TermsOfService:
                ((HyperLink)ctl).NavigateUrl        =   HttpUrlBuilder.BuildUrl("~/editprofile.aspx",true,DynPageLoc.Secured,StStr.PageEditProfileID);
                if (SecurityTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM InitializeComponent EditProfileLinkSuccess: {0}.", ((HyperLink)ctl).NavigateUrl), SecurityTraceSwitch.Sw.Info);
            }
            */
        }
        
        #endregion Std overrides
    }
}